import { reactive } from 'vue';

export default function useCity(cityQuery, api_key, error) {
  const city = reactive({
    name: '',
    id: '',
  });
  const fetchCity = () => {
    return new Promise((resolve, reject) => {
      fetch(
        `https://geoapi.qweather.com/v2/city/lookup?location=${cityQuery.value}&key=${api_key}`
      )
        .then((res) => res.json())
        .then((res) => {
          if (res.code === '200') {
            city.id = res.location[0].id;
            city.name = res.location[0].name;
            error.state = false;
            resolve();
          } else {
            error.state = true;
            error.msg = '城市未找到';
            reject('城市出错');
          }
        });
    });
  };
  return {
    city,
    fetchCity,
  };
}
